package com.softlook.mt.server;

import java.util.ArrayList;
import java.util.Date;
import java.sql.Timestamp;
import java.util.Iterator;

import javax.servlet.*;
import javax.servlet.http.*;

import com.google.gwt.user.server.rpc.RemoteServiceServlet;
import com.softlook.mt.client.bricks.monitor.*;
import com.softlook.mt.client.data.*;

import com.softlook.mt.server.bo.*;
import com.softlook.mt.server.db.dto.Gpsdata;

public class MonitorServiceImpl extends RemoteServiceServlet implements MonitorService {


	private DeviceCollection m_allDevices;
	private DeviceCollection m_chekedDevices;
	private BOUser m_user = new BOUser();
	
	public MonitorServiceImpl(){
            try {
                if(!m_user.isLoggedIn()) m_user.login("userlogin1", "userpwd1", Integer.valueOf(1));
            } catch (Exception ex) {
                ex.printStackTrace();
            }
            m_allDevices = new DeviceCollection();
            m_chekedDevices = new DeviceCollection();

            /*
            DeviceTrack device1 = new DeviceTrack();
            DeviceTrack device2 = new DeviceTrack();
            DeviceTrack device3 = new DeviceTrack();
            DeviceTrack device4 = new DeviceTrack();

            device1.set(1,"test dev 1", 53.906, 27.578,
                            "k~_hI{xhgDoMaOwVuWkPm[q^owA_Ect@eH}b@mf@wuCuc@s~Bk[s`BuPmq@{StPlC`O`JvIlC|LaJ|b@{@gCxAcH_DDaBWQe@",
                            "BBBBBBBBBBBBBBBBBBBBB",
                            "#00FF00");
            device2.set(2,"test dev 2", 53.907, 27.575,
                            "{l`hIweigDjGoQgJ_NoKkSeJ`RvCnJsBlEaGaK",
                            "BAB@AA@B",
                            "#0000FF");
            device3.set(3,"test dev 3", 53.902, 27.572);
            device4.set(4,"test dev 4", 53.909, 27.574);

            m_allDevices = new DeviceCollection();
            m_allDevices.add(device1);
            m_allDevices.add(device2);
            m_allDevices.add(device3);
            m_allDevices.add(device4);
		
            m_chekedDevices = new DeviceCollection();
            m_chekedDevices.add(device1);
            m_chekedDevices.add(device2);
            m_chekedDevices.add(device3);
            m_chekedDevices.add(device4);
            */
	}
	
	private void emulateDevicePosition(){
		final int k = 1000;
		Iterator deviceIterator = m_chekedDevices.iterator( );
                int n=0;
		
		while (deviceIterator.hasNext( )) {
                        n++;
			Device device = (Device) deviceIterator.next();
			Gpsdata gpsdata = new Gpsdata();
                        gpsdata.setDeviceid(device.getId());
                        gpsdata.setLat(Double.valueOf(53.900 + n*0.001 + (Math.random()-0.5)*2/k));
                        gpsdata.setLon(Double.valueOf(27.570 + n*0.001 + (Math.random()-0.5)*2/k));
                        gpsdata.setTime(new Timestamp((new Date()).getTime()));
                        BOGpsdata boGpsdata = new BOGpsdata();
                        try{
                            boGpsdata.add(gpsdata);
                        }catch(Exception ex){
                            
                        }
                        
			//device.setPoint(device.getLat()+ (Math.random()-0.5)*2/k , device.getLng()+(Math.random()-0.5)*2/k);
		}
	}

	public DeviceCollection getAllDevices() {
            try {
                Iterator it = m_user.getDevices().iterator();
                m_allDevices = new DeviceCollection();
                while(it.hasNext()){
                    BODevice boDevice = (BODevice) it.next();
                    Device device = new DeviceTrack();
                    
                    BOGpsdata boGpsdata = boDevice.getLastPosition();
                    /*if(boGpsdata != null) {
                        System.out.println("device lat = "+boGpsdata.get().getLat().toString());
                        System.out.println("device lon = "+boGpsdata.get().getLon().toString());
                    }*/
                    
                    device.set(boDevice.get().getDeviceid().intValue(), boDevice.get().getName(), boGpsdata.get().getLat().doubleValue(), boGpsdata.get().getLon().doubleValue());
                    m_allDevices.add(device);
                }
            } catch (Exception ex) {
                ex.printStackTrace();
            }
            return m_allDevices;
	}
	
	public DeviceCollection getCheckedDevices(){
            emulateDevicePosition();
            
            try {
                Iterator it = m_user.getCheckedDevices().iterator();
                m_chekedDevices = new DeviceCollection();
                while(it.hasNext()){
                    BODevice boDevice = (BODevice) it.next();
                    Device device = new DeviceTrack();
                    
                    BOGpsdata boGpsdata = boDevice.getLastPosition();
                    /*if(boGpsdata != null) {
                        System.out.println("device lat = "+boGpsdata.get().getLat().toString());
                        System.out.println("device lon = "+boGpsdata.get().getLon().toString());
                    }*/
                    
                    device.set(boDevice.get().getDeviceid().intValue(), boDevice.get().getName(), boGpsdata.get().getLat().doubleValue(), boGpsdata.get().getLon().doubleValue());
                    m_chekedDevices.add(device);
                }
            } catch (Exception ex) {
                ex.printStackTrace();
            }
            return m_chekedDevices;
	}

	public DeviceCollection getCheckedDeviceTracks(Date dateBegin, Date dateEnd){
			//System.out.println("beginDate "+dateBegin.toLocaleString() +" ; dateEnd "+dateEnd.toLocaleString() );
            String colors[] = new String[] {"#0000FF", //let we paint devices with defferent colors
                                            "#00FF00",
                                            "#FF0000",
                                            "#FFFF00",
                                            "#00FFFF",
                                            "#FF00FF",
                                            "#B0B0B0",
                                            "#B000B0",
                                            "#00B0B0",
                                            "#B0B000",
                                            "#0000B0",
                                            "#00B000",
                                            "#B00000"
                                            };
            int colorNumber = 0;
            try {
                Iterator it = m_user.getCheckedDevices().iterator();
                m_chekedDevices = new DeviceCollection();
                while(it.hasNext()){
                    BODevice boDevice = (BODevice) it.next();
                    DeviceTrack device = new DeviceTrack();

                    BOGpsdata boGpsdata = boDevice.getLastPosition();

                    StringBuffer levels = new StringBuffer();
                    String track = boDevice.getGoogleTrack(dateBegin, dateEnd, levels);

                    
                    device.set(boDevice.get().getDeviceid().intValue(),
                            boDevice.get().getName(), boGpsdata.get().getLat().doubleValue(), boGpsdata.get().getLon().doubleValue(),
                                    track,
                                    levels.toString(),
                                    colors[colorNumber]);
                    m_chekedDevices.add(device);
                    colorNumber++;
                    if(colorNumber>12) colorNumber = 0;
                    
                    //System.out.println("device["+device.getId()+"] = "+device.getTrack());
                }
            } catch (Exception ex) {
                ex.printStackTrace();
            }
            return m_chekedDevices;
	}
	
	public void checkDevice(Integer id, boolean isChecked){
		//System.out.println("isChecked: "+isChecked);
            if (isChecked){
                    Device device = m_allDevices.getDevice(id);
                    m_chekedDevices.add(device);
            }else{
                    m_chekedDevices.remove(id);
            }
            try {
                m_user.setCheckedDevice(id, isChecked);
            } catch (Exception ex) {
                
            }
	}
}
